package com.app.couponsharelife.ui.main.me.team
import android.content.Intent
import android.graphics.drawable.AnimationDrawable
import android.text.InputFilter
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.bean.UserTeamMemberBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.adapter.MyTeamListAdapter
import com.app.couponsharelife.ui.main.me.invite.ShareInvitePicActivity
import com.app.couponsharelife.utils.AppUtils
import com.scwang.smartrefresh.layout.api.RefreshFooter
import com.scwang.smartrefresh.layout.api.RefreshHeader
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.constant.RefreshState
import com.scwang.smartrefresh.layout.listener.OnMultiPurposeListener
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_teamsearch.*
import kotlinx.android.synthetic.main.base_refresh_head.*
import kotlinx.android.synthetic.main.base_title_search_white.*
import java.util.HashMap

/**
 *Created by xct on 2019/3/20
 *Description:团队成员搜索结果页面
 */
class TeamSearchListActivity:BaseActivity() {
    private var pageIndex=1
    private var keyWord=""
    private var dataList= arrayListOf<UserTeamMemberBean.RecordsBean>()
    private var adapter:MyTeamListAdapter?=null
    override val viewLayoutId: Int
        get() = R.layout.activity_teamsearch

    override fun initViews() {
        AppUtils.initImmersionBar(this,true)
        basetitle_edit.hint="输入用户名查找团队成员"
        keyWord=intent.getStringExtra("KeyWord")?:""
        if (keyWord.isEmpty()){
            showToastMsg("搜索内容不能为空！")
            finish()
        }
        basetitle_edit.filters=arrayOf<InputFilter>(InputFilter.LengthFilter(12))
        basetitle_edit.setText(keyWord)
        basetitle_edit.setSelection(keyWord.length)
        basetitle_llclose.setOnClickListener {
            AppUtils.hideInputBoard(this,basetitle_edit)
            finish()
        }
        basetitle_edit.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH){
                val keyWords=basetitle_edit.text.toString().trim()
                if (keyWords.isNotEmpty()){
                    teamsearch_smartrefresh.resetNoMoreData()
                    keyWord=keyWords
                    pageIndex=1
                    getData(false)
                }else{
                    showToastMsg("请输入搜索内容！")
                }
                true
            }else{
                false
            }
        }
        basetitle_imag_delete.setOnClickListener { basetitle_edit.setText("") }
        teamsearch_llContent.setOnClickListener { startActivity(Intent(this,ShareInvitePicActivity::class.java)) }
        setRefresh()
        teamsearch_rv.layoutManager= LinearLayoutManager(this)
        adapter= MyTeamListAdapter(this,dataList)
        teamsearch_rv.adapter=adapter
        getData(false)
    }
    private fun setRefresh(){
        hotsale_refreshimg.setImageResource(R.drawable.anim_refresh)
        val animationDrawable=hotsale_refreshimg.drawable as AnimationDrawable
        teamsearch_smartrefresh.setOnMultiPurposeListener(object : OnMultiPurposeListener {
            override fun onFooterMoving(footer: RefreshFooter?, isDragging: Boolean, percent: Float, offset: Int, footerHeight: Int, maxDragHeight: Int) {

            }

            override fun onHeaderStartAnimator(header: RefreshHeader?, headerHeight: Int, maxDragHeight: Int) {

            }

            override fun onFooterReleased(footer: RefreshFooter?, footerHeight: Int, maxDragHeight: Int) {

            }

            override fun onStateChanged(refreshLayout: RefreshLayout, oldState: RefreshState, newState: RefreshState) {

            }

            override fun onHeaderMoving(header: RefreshHeader?, isDragging: Boolean, percent: Float, offset: Int, headerHeight: Int, maxDragHeight: Int) {
                setAnima(percent)
            }

            override fun onFooterFinish(footer: RefreshFooter?, success: Boolean) {

            }

            override fun onFooterStartAnimator(footer: RefreshFooter?, footerHeight: Int, maxDragHeight: Int) {

            }

            override fun onHeaderReleased(header: RefreshHeader?, headerHeight: Int, maxDragHeight: Int) {
                animationDrawable.start()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                getData(false)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex=1
                getData(true)
            }

            override fun onHeaderFinish(header: RefreshHeader?, success: Boolean) {
                hotsale_refreshimg.setImageResource(R.drawable.refresh_0)
                animationDrawable.stop()
            }
        })
    }
    private fun setAnima(vlaue:Float){
        val layoutParams=hotsale_refreshimg.layoutParams as ConstraintLayout.LayoutParams
        layoutParams.matchConstraintPercentHeight=vlaue/2
        layoutParams.dimensionRatio="0.875:1"
        hotsale_refreshimg.layoutParams=layoutParams
    }
    private fun getData(isRefresh:Boolean){
        if (!isRefresh&&pageIndex==1){
            showProgressDialog("加载中...")
        }
        val map= HashMap<String,String>()
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        map["pageNo"] = pageIndex.toString()
        map["pageSize"] = "15"
        map["keyword"] = keyWord
        RetrofitWorker.retrofitWorker.getSearchTeamList(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<UserTeamMemberBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<UserTeamMemberBean>) {
                        if (it.code==200&&it.data!=null){
                            if (!isRefresh&&pageIndex==1){
                                dismissProgressDialog()
                            }
                            if (it.data!=null&&it.data!!.records!!.isNotEmpty()){
                                if (pageIndex==1){
                                    dataList.clear()
                                    teamsearch_llerror.visibility= View.GONE
                                    teamsearch_rv.visibility= View.VISIBLE
                                    if (isRefresh){
                                        teamsearch_smartrefresh.finishRefresh()
                                    }
                                }else{
                                    teamsearch_smartrefresh.finishLoadMore()
                                }
                                dataList.addAll(it.data!!.records!!)
                                if (it.data!!.records!!.size<10){
                                    val recordsBean=UserTeamMemberBean.RecordsBean()
                                    recordsBean.grade=""
                                    dataList.add(recordsBean)
                                    teamsearch_smartrefresh.finishLoadMoreWithNoMoreData()
                                }
                                pageIndex++
                                adapter!!.notifyDataSetChanged()
                            }else{
                                if (isRefresh){
                                    teamsearch_smartrefresh.finishRefresh()
                                }
                                if (pageIndex==1&&dataList.size==0){
                                    teamsearch_smartrefresh.finishLoadMoreWithNoMoreData()
                                    teamsearch_llerror.visibility= View.VISIBLE
                                    teamsearch_rv.visibility= View.GONE
                                }
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (!isRefresh&&pageIndex==1){
                            dismissProgressDialog()
                        }
                        if (isRefresh){
                            teamsearch_smartrefresh.finishRefresh()
                        }
                        if (pageIndex>1){
                            teamsearch_smartrefresh.finishLoadMore()
                        }
                        if (pageIndex==1){
                            teamsearch_smartrefresh.finishLoadMoreWithNoMoreData()
                            teamsearch_llerror.visibility= View.VISIBLE
                            teamsearch_rv.visibility= View.GONE
                        }
                        if (e is OtherException){
                            //showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }
                })
    }
    override fun onDestroy() {
        super.onDestroy()
        AppUtils.destroyImmersionBar(this)
    }
}